import sys,re
from typing import List
from enum import Enum

class RegEnum(Enum):
    """ 
        MDC:str.匹配MDC的正则表达式
        MDC_GROUP:str.用于分组引用时的MDC正则表达式
        ADRG:str.匹配ADRG的正则表达式
        ADRG_GROUP:str.用于分组引用时匹配ADRG的正则表达式
        ICD_DISEASE:str.匹配疾病和手术编码的正则达表式
        SPLIT_KEY:str.用于分割字符串的正则达表式
    """

    MDC=r"\b[' ']{0,3}M[' ']{0,3}D[' ']{0,3}C[' ']{0,3}[A-Z]"
    MDC_GROUP=r"(\b[' ']{0,3}M[' ']{0,3}D[' ']{0,3}C[' ']{0,3}[A-Z])"
    ADRG=r"[' ']{0,3}[A-Z][' ']{0,3}[A-Z][' ']{0,3}[0-9]\b"
    ADRG_GROUP=r"([' ']{0,3}[A-Z][' ']{0,3}[A-Z][' ']{0,3}[0-9]\b)"
    ICD_DISEASE=r'\b[A-Z\d]{2,3}\.[x\d]{2,3}\d(?:x\d{3})?(?:\+[A-Z]\d{2}\.\d\*)?'
    EC_SHEET_NAME=r"[' ']{0,3}表[' ']{0,3}6[' ']{0,3}-[' ']{0,3}3[' ']{0,3}-[' ']{0,3}\d{1,3}"
    REF_NEW_LINE=r'\n\1\n'
    SPLIT_KEY=r'\n'

def description(text:str)->str:
    """    检查text中是否包含了:"包含以下主要手术或操作"等关键字，如果包含则返回text，否则返回空字符串    """
    context=text.replace(' ','')
    pattern=['包含以下主要手术或操作','同时包含以下手术','包含以下主要诊断','主要诊断','诊断','手术','和','操作']
    matches=''
    for p in pattern:
        if p in context:
            matches=context
            break
    return matches


def exctract_adrg_code(text:str)->str:
    """    从文本中提取ADRG编码    """

    ADRG_LIST=['AA1', 'AA2', 'AB1', 'AC1', 'AD1', 'AE1', 'AF1', 'AG1', 'AG2', 'AG3', 'AH1', 'AH2', 'BB1', 'BB2', 'BB3', 'BB4', 'BB5', 'BC1', 'BD1', 'BD2', 'BE1', 'BE2', 'BJ1', 'BL1', 'BM1', 'BR1', 'BR2', 'BS1', 'BT1', 'BT2', 'BT3', 'BU1', 'BU2', 'BU3', 'BV1', 'BV2', 'BV3', 'BW1', 'BW2', 'BX1', 'BX2', 'BY1', 'BY2', 'BZ1', 'CB1', 'CB2', 'CB3', 'CB4', 'CB5', 'CB6', 'CB7', 'CD1', 'CD2', 'CD3', 'CJ1', 'CR1', 'CS1', 'CT1', 'CU1', 'CV1', 'CW1', 'CX1', 'CZ1', 'DB1', 'DB2', 'DC1', 'DC2', 'DC3', 'DC4', 'DD1', 'DD2', 'DE1', 'DE2', 'DF1', 'DF2', 'DG1', 'DG2', 'DH1', 'DH2', 'DH3', 'DH4', 'DJ1', 'DK1', 'DR1', 'DS1', 'DT1', 'DT2', 'DU1', 'DV1', 'DW1', 'DZ1', 'EB1', 'EB2', 'EC1', 'EC2', 'ED1', 'EJ1', 'EK1', 'EK2', 'ER1', 'ER2', 'ES1', 'ES2', 'ES3', 'ET1', 'ET2', 'EU1', 'EV1', 'EW1', 'EX1', 'EX2', 'EZ1', 'FB1', 'FB2', 'FC1', 'FD1', 'FD2', 'FE1', 'FE2', 'FF1', 'FF2', 'FF3', 'FJ1', 'FK1', 'FK2', 'FK3', 'FK4', 'FL1', 'FL2', 'FL3', 'FL4', 'FM1', 'FM2', 'FM3', 'FM4', 'FM5', 'FN1', 'FN2', 'FP1', 'FR1', 'FR2', 'FR3', 'FR4', 'FR5', 'FT1', 'FT2', 'FT3', 'FT4', 'FU1', 'FU2', 'FV1', 'FV2', 'FV3', 'FW1', 'FW2', 'FZ1', 'GB1', 'GB2', 'GB3', 'GC1', 'GC2', 'GC3', 'GD1', 'GE1', 'GE2', 'GF1', 'GF2', 'GF3', 'GG1', 'GG2', 'GH1', 'GJ1', 'GK1', 'GK2', 'GK3', 'GR1', 'GS1', 'GT1', 'GU1', 'GU2', 'GV1', 'GW1', 'GZ1', 'HB1', 'HC1', 'HC2', 'HC3', 'HJ1', 'HK1', 'HL1', 'HL2', 'HR1', 'HS1', 'HS2', 'HS3', 'HT1', 'HT2', 'HU1', 'HZ1', 'HZ2', 'HZ3', 'IB1', 'IB2', 'IB3', 'IC1', 'IC2', 'IC3', 'IC4', 'ID1', 'ID2', 'IE1', 'IE2', 'IE3', 'IE4', 'IE5', 'IE6', 'IF1', 'IG1', 'IH1', 'IJ1', 'IR1', 'IR2', 'IS1', 'IS2', 'IT1', 'IT2', 'IT3', 'IU1', 'IU2', 'IU3', 'IV1', 'IZ1', 'IZ2', 'JA1', 'JA2', 'JB1', 'JB2', 'JB3', 'JC1', 'JD1', 'JD2', 'JJ1', 'JR1', 'JR2', 'JS1', 'JS2', 'JT1', 'JU1', 'JV1', 'JV2', 'JZ1', 'KB1', 'KC1', 'KD1', 'KD2', 'KE1', 'KJ1', 'KR1', 'KS1', 'KT1', 'KU1', 'KV1', 'KZ1', 'LA1', 'LA2', 'LB1', 'LB2', 'LC1', 'LD1', 'LE1', 'LF1', 'LJ1', 'LL1', 'LR1', 'LS1', 'LT1', 'LU1', 'LV1', 'LW1', 'LX1', 'LZ1', 'MA1', 'MB1', 'MC1', 'MD1', 'MJ1', 'MR1', 'MS1', 'MZ1', 'NA1', 'NA2', 'NB1', 'NC1', 'ND1', 'NE1', 'NF1', 'NG1', 'NJ1', 'NR1', 'NS1', 'NZ1', 'OB1', 'OC1', 'OC2', 'OD1', 'OD2', 'OE1', 'OF1', 'OF2', 'OJ1', 'OR1', 'OS1', 'OS2', 'OT1', 'OZ1', 'PB1', 'PC1', 'PD1', 'PJ1', 'PK1', 'PR1', 'PS1', 'PS2', 'PS3', 'PS4', 'PU1', 'PV1', 'QB1', 'QJ1', 'QR1', 'QR2', 'QS1', 'QS2', 'QS3', 'QS4', 'QS5', 'QT1', 'RA1', 'RA2', 'RA3', 'RA4', 'RK1', 'RK2', 'RL1', 'RL2', 'RM1', 'RN1', 'RN2', 'RP1', 'RR1', 'RS1', 'RS2', 'RT1', 'RT2', 'RU1', 'RW1', 'RW2', 'SB1', 'SR1', 'SS1', 'ST1', 'SU1', 'SV1', 'SZ1', 'TB1', 'TR1', 'TR2', 'TS1', 'TS2', 'TT1', 'TT2', 'TU1', 'TV1', 'TW1', 'TX1', 'TY1', 'UR1', 'US1', 'VB1', 'VC1', 'VJ1', 'VR1', 'VS1', 'VS2', 'VT1', 'VZ1', 'WB1', 'WB2', 'WB3', 'WJ1', 'WR1', 'WR2', 'XJ1', 'XR1', 'XR2', 'XR3', 'XS1', 'XS2', 'XT1', 'XT2', 'XT3', 'YC1', 'YR1', 'YR2', 'ZB1', 'ZC1', 'ZD1', 'ZJ1', 'ZZ1']
    # pattern = r"^[' ']{0,3}[A-Z][' ']{0,3}[A-Z][' ']{0,3}[0-9]\b" 
    matches = re.search(RegEnum.ADRG.value, text)
    matches=matches.group().replace(' ','') if matches else ''
    # matches = [match.replace(' ','') for match in matches]
    matches=matches if matches in ADRG_LIST else ''
    return matches

def extract_mdc_code(text:str)->str:

    # pattern = r"\b[' ']{0,3}M[' ']{0,3}D[' ']{0,3}C[' ']{0,3}[A-Z]"      
    matches = re.search(RegEnum.MDC.value, text)    
    matches=matches.group().replace(' ','') if matches else ''
    # matches = [match.replace(' ','') for match in matches]
    return matches


def extract_icd10_codes(text:str)->List:
    """:
    从文本中提取ICD-10编码 
    """ 
    # 定义ICD-10编码的正则表达式  
    # pattern=r'\b[A-Z\d]{2,3}\.[0-9]{3,4}(?:x\d{3})?(?:\+[A-Z]\d{2}\.\d\*)?'   #匹配ICD10疾病编码、手术编码
    # pattern=r'\b[A-Z\d]{2,3}\.[x\d]{2,3}\d(?:x\d{3})?(?:\+[A-Z]\d{2}\.\d\*)?'   #匹配ICD10疾病编码、手术编码
    # 使用正则表达式查找所有匹配项  
    matches = re.findall(RegEnum.ICD_DISEASE.value, text)
    return matches


def extract_ruleout_sheetname(text:str)->str:
    """
    从文本中提取"表6-1"、"表 6-211"等"排除表"名称
    """
    # pattern=r"[' ']{0,3}表[' ']{0,3}7[' ']{0,3}-[' ']{0,3}\d{1,3}"
    matches=re.findall(RegEnum.EC_SHEET_NAME.value,text) 
    sheetname=''
    if len(matches)>0:
        sheetname=matches[0].replace(' ','')
    return sheetname


def to_txt(data:List[str],filename:str):    
    with open(filename, 'w',encoding='utf-8') as file:  
    # 遍历列表中的每个元素
        for item in data:
            file.write("%s\n" % item)
          

def extract_about_drgs(filepath_sourth:str=''):
    """
    从CHS-DRG 核心疾病诊断相关分组中提取MDC主诊表、ADRG诊断表
    """  
    filepath_sourth='DRG_GROUPS.txt' if len(filepath_sourth)==0 else filepath_sourth
    current_node_title=''
    current_node=''              # MDC or ADRG
    mdc_disease_list=[]
    adrg_disease_list=[]
    descript_list=[]

    with open(filepath_sourth, 'r', encoding='utf-8') as file:  
        # 逐行读取  
        for line_txt in file:  
            line_text=line_txt.strip()
            line_text=re.sub(RegEnum.MDC_GROUP.value,RegEnum.REF_NEW_LINE.value,line_text)     # 给每个MDC名称后面加上换行符\n
            line_text=re.sub(RegEnum.ADRG_GROUP.value,RegEnum.REF_NEW_LINE.value,line_text)    # 给每个ADRG名称后面加上换行符\n
            line_list=re.split(RegEnum.SPLIT_KEY.value,line_text)                              # 按换行符\n分割字符串
            # print(line_list)

            for line in line_list:            
                mdc_code=extract_mdc_code(line)
                if len(mdc_code)>0:
                    current_node_title=mdc_code
                    current_node='MDC'
                    continue

                adrg_code=exctract_adrg_code(line)
                if len(adrg_code)>0:
                    current_node_title=adrg_code
                    current_node='ADRG'
                    continue        

                icd_codes=extract_icd10_codes(line)
                if len(icd_codes)>0:
                    if current_node=='MDC':
                        mdc_disease_list.append('\n'.join([current_node_title+"-"+icd_code for icd_code in icd_codes]))
                    elif current_node=='ADRG':
                        adrg_disease_list.append('\n'.join([current_node_title+"-"+icd_code for icd_code in icd_codes]))
                    continue

                descript_list.append(f"{current_node_title}:{line}")

            # description=exctract_description(line)
            # if len(description)>0:
            #     descript_list.append(f"{current_node_title}: {description}")
            #     continue
    to_txt(mdc_disease_list,'mdc_disease_list.txt')
    to_txt(adrg_disease_list,'adrg_disease_list.txt')
    to_txt(descript_list,'descript_list.txt')
    # print('----mdc_disease_list----')
    # print(mdc_disease_list)
    # print('----adrg_disease_list----')
    # print(adrg_disease_list)
    # print('----descript_list----')
    # print(descript_list)


def extract_ruleout_sheets(input_file:str):
    """
    从CHS-DRG 提取MCC\CC排除表
    """
    current_sheetname=''
    ruleout_sheet_disease_list=[]
    descript_list=[]
    with open(input_file, 'r', encoding='utf-8') as file:
        for line in file:
            line_text=line.strip()

            ruleout_sheetname=extract_ruleout_sheetname(line_text)
            if len(ruleout_sheetname)>0:
                current_sheetname=ruleout_sheetname
                continue

            icd_codes=extract_icd10_codes(line_text)
            if len(icd_codes)>0:
                ruleout_sheet_disease_list.append('\n'.join([current_sheetname+" "+icd_code for icd_code in icd_codes]))
                continue

            descript_list.append(f"{current_sheetname}:{line_text}")

    to_txt(ruleout_sheet_disease_list,'ruleout_sheet_disease.txt')
    to_txt(descript_list,'ruleout_sheet_descript.txt')    


if __name__ == '__main__':
    # extract_about_drgs()
    # extract_ruleout_sheets()
    # txt='AA1,AA2,AB1,AC1,AD1,AE1,AF1,AG1,AG2,AG3,AH1,AH2,BB1,BB2,BB3,BB4,BB5,BC1,BD1,BD2,BE1,BE2,BJ1,BL1,BM1,BR1,BR2,BS1,BT1,BT2,BT3,BU1,BU2,BU3,BV1,BV2,BV3,BW1,BW2,BX1,BX2,BY1,BY2,BZ1,CB1,CB2,CB3,CB4,CB5,CB6,CB7,CD1,CD2,CD3,CJ1,CR1,CS1,CT1,CU1,CV1,CW1,CX1,CZ1,DB1,DB2,DC1,DC2,DC3,DC4,DD1,DD2,DE1,DE2,DF1,DF2,DG1,DG2,DH1,DH2,DH3,DH4,DJ1,DK1,DR1,DS1,DT1,DT2,DU1,DV1,DW1,DZ1,EB1,EB2,EC1,EC2,ED1,EJ1,EK1,EK2,ER1,ER2,ES1,ES2,ES3,ET1,ET2,EU1,EV1,EW1,EX1,EX2,EZ1,FB1,FB2,FC1,FD1,FD2,FE1,FE2,FF1,FF2,FF3,FJ1,FK1,FK2,FK3,F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UR1,US1,VB1,VC1,VJ1,VR1,VS1,VS2,VT1,VZ1,WB1,WB2,WB3,WJ1,WR1,WR2,XJ1,XR1,XR2,XR3,XS1,XS2,XT1,XT2,XT3,YC1,YR1,YR2,ZB1,ZC1,ZD1,ZJ1,ZZ1'
    # ADRG_LIST=txt.split(',')
    # print(ADRG_LIST)
    extract_ruleout_sheets('ec.txt')
    print('end')
    
    # l=["12.1100x002","12.1101","12.1200x001","12.1201","12.1202","12.1203","12.1300","12.1400x001","12.1400x008","12.1401","12.1402","12.1403","12.1404","12.3100","12.3200x001","12.3300","12.3301","12.3500","12.3501","12.3502","12.3503","12.3504","12.3900x001","12.3900x004","12.3901","12.3902","12.4100x001","12.4100x002","12.4100x003","12.4100x004","12.4401","12.6301","12.9701","12.9702","12.9703"]
    # print('\n'.join(l))